from info.response import RET
from . import admin_blueprint
from flask import render_template,redirect,request,current_app,session, jsonify
from info .models import User, News, Category
from info import constants, db
from datetime import datetime, timedelta



@admin_blueprint.route('/login' , methods = ["GET" , "POST"])
def login():
    if request.method == "GET":
        data = {'msg':''}
        return render_template('admin/login.html' , data = data)
    #POST 请求下 处理逻辑
    # 接受
    #     接受用户输入的账户密码,from表单提交request.form
    username = request.form.get('username')
    password = request.form.get('password')
    # 验证
    #     验证用户输入的是否非空
    if not all ([username,password]):
        data = {'msg' : '信息不能为空'}
        return render_template('admin/login.html', data = data)

    # 处理
    #     创建对象查询,User 精确查找 mobile  = admin =True).firsr()
    #     使用捕获异常
    try:
        user = User.query.filter_by(mobile = username , is_admin = True).first()
    except Exception as e:
        current_app.logger.error(e)
        data = {'msg' : '数据库链接失败'}
        return render_template('admin/login.html', data = data)
    if user is None:
        data = {'msg' : '用户名错误'}
        return render_template('admin/login.html',data = data)
    if user.check_password(password):
        session['admin_user_id'] = user.id
        return redirect('/admin/')

    else:
        data = {'msg' : '密码错误'}
        return render_template('admin/login.html',data = data)

#     响应
# 退出功能
@admin_blueprint.route('/logout')
def logout():
    #退出,就删除状态保持.参数里写当前登录的用户名
    session.pop('admin_user_id')
    #返回,因为推出了要跳转到admin的登录界面
    return redirect('/admin/login')


# 管理原页展示功能
@admin_blueprint.route('/')
def index():
    try:
        user = User.query.get(session['admin_user_id'])
    except Exception as  e:
        current_app.logger.error(e)
    data = {
        #当前登录用户名 判断一下 登录下不报错
        'name' : user.nick_name if user else None,
        #用户头像路径 拼接写成七牛云路径
        'avatar_url' : constants.QINIU_DOMIN_PREFIX + user.avatar_url if user else None
    }
    return render_template('admin/index.html',data = data)


# 用户统计功能
@admin_blueprint.route('/user_count')
def user_count():
    # 获取数据,获取用户总数
    count_total = User.query.filter_by(is_admin = False).count()
    # 获取当前时间
    now = datetime.now()
    # 做个时间判断,需要知道当前时间[datetime==创建日期对象,参数为年,月,日,时,分,秒]
    month_first = datetime(now.year, now.month, 1)
    # 用户月新增
    #查看用户创建的时间在本悦之内,大于或者等于一号之内日期
    count_month = User.query.filter(User.create_time >= month_first,User.is_admin == False).count()

    # 用户日新增
    day_first = datetime(now.year,now.month,now.day)
    count_day = User.query.filter(User.create_time >= day_first,User.is_admin == False).count()
    # 登录信息,近30天中,每天的登录信息
    # datetime-datetime====>timedelta
    xlist =[]
    ylist =[]
    for i in range(0,10):
        # 将i = 0,i = 1, i = 2 带入公式
        day_begin = day_first-timedelta(days = i+1)
        day_end  = day_first-timedelta(days = i)
        #统计
        xlist.append(day_begin.strftime('%Y-%m-%d'))
        count=User.query.filter_by(is_admin=False). \
            filter(User.update_time>=day_begin,User.update_time<day_end).count()
        ylist.append(count)
    xlist.reverse()
    ylist.reverse()

    data = {

        'count_total': count_total,
        'count_month': count_month,
        'count_day': count_day,
        'xlist':xlist,
        'ylist':ylist
    }
    return render_template('admin/user_count.html', data = data)

@admin_blueprint.route('/user_list')
def user_list():
    try:
        page= int(request.args.get('page' , 1))
    except:
        page = 1

    pagination = User.query.\
        filter_by(is_admin = False).\
        order_by(User.id.desc()).\
        paginate(page,constants.ADMIN_USER_PAGE_MAX_COUNT, False)
    user_list2 = [user.to_admin_dict()for user in pagination.items]

    data = {
        'user_list' : user_list2,
        'page' : page,
        'total_page' : pagination.pages
    }
    return render_template('admin/user_list.html',data = data)

@admin_blueprint.route('/news_review')
def news_review():
    # GET 请求方式,无论是超链接,表单,还是ajax只要GET方式的请求,都用request.args接受
    title = request.args.get('title' ,'')
    try:
        page = int(request.args.get('page' ,1))
    except:
        page = 1

    pagination = News.query.filter_by(status = 1)

    if title:
        pagination = pagination.filter(News.title.contains(title))
        #
    pagination = pagination.order_by(News.id.desc()).paginate(page,constants.ADMIN_NEWS_PAGE_MAX_COUNT,False)
    news_list = [news.to_release_dict() for news in pagination.items]
    data = {
        'news_list' : news_list,
        'page' : page,
        'total_page' : pagination.pages,
        'title' : title
    }
    return render_template('admin/news_review.html', data = data)


@admin_blueprint.route('/news_review_detail', methods = ['GET','POST'])
def news_review_detail():
    if request.method == 'GET':
        news_id = request.args.get('news_id')

        try:
            news = News.query.get(news_id)
        except Exception as e:
            current_app.logger.error(e)
            return redirect('admin/news_review')
        if news is None:
            return redirect('admin/news_review')
        data = {'news' : news}
        return render_template('admin/news_review_detail.html', data = data)

#POST 请求审核处理
    #接受
    action = request.json.get('action')
    news_id = request.json.get('news_id')
    reason = request.json.get('reason')
    if not all ([action,news_id]):
        return jsonify(erron = RET.DATAERR,errmsg = '数据不完整')
    try:
        news = News.query.get(news_id)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno = RET.DBERR, errmsg = '查询新闻失败')
    if action == 'accept':
        news.status = 0
    elif action == 'reject':
        news.status = -1
        #失败原因reason
        news.reason = reason
    try:
        db.session.commit()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno = RET.DBERR,errmsg = '审核失败')
    return jsonify(errno = RET.OK,errmsg = '')



@admin_blueprint.route('/news_type')
def news_type():
    try:
        category_list = Category.query.all()
    except Exception as e:
        current_app.logger.error(e)
        category_list = []
    data = {
        'category_list': category_list
    }
    return render_template('admin/news_type.html', data = data)


@admin_blueprint.route('/add_category', methods = ['POST'])
def add_category():
#接受
    #新闻分类的名字
    name = request.json.get('name')
    #新闻的id
    cid = request.json.get('id')
    if not name:
        return jsonify(errno = RET.DATAERR,errmsg = '请先输入分类名字')
    if cid is None:
        #添加
        category = Category()
        category.name = name
        db.session.add(category)
    else: #修改
        try:
            category = Category.query.get(cid)
        except Exception as e:
            current_app.logger.error(e)
            return jsonify(errno = RET.DBERR,errmsg = '查询分类失败')
        if category is None:
            return jsonify(errno = RET.DATAERR, errmsg= '编号不存在')
        category.name = name
    #提交数据库
    try:
        db.session.commit()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno = RET.DBERR, errmsg = '保存信息失败')
    return jsonify(errno = RET.OK, errmsg = '')